package com.xmmj.baselibrary.base.activity.swipeback

import android.app.Activity
import android.view.MotionEvent
import com.xmmj.baselibrary.base.activity.swipeback.SwipeBackHelper.SlideBackManager
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import com.xmmj.baselibrary.R

/**
 * 支持侧滑关闭的Activity
 */
open class SwipeBackActivity : RxAppCompatActivity(), SlideBackManager {
    private var mSwipeBackHelper: SwipeBackHelper? = null
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (!supportSlideBack()) {
            return super.dispatchTouchEvent(ev)
        }
        if (mSwipeBackHelper == null) {
            mSwipeBackHelper = SwipeBackHelper(this, SlideActivityAdapter())
            mSwipeBackHelper!!.setOnSlideFinishListener {
                finish()
                overridePendingTransition(android.R.anim.fade_in, R.anim.hold_on)
            }
        }
        return mSwipeBackHelper!!.processTouchEvent(ev) || super.dispatchTouchEvent(ev)
    }

    override fun finish() {
        if (mSwipeBackHelper != null) {
            mSwipeBackHelper!!.finishSwipeImmediately()
        }
        super.finish()
    }

    override fun supportSlideBack(): Boolean {
        return true
    }

    override fun canBeSlideBack(): Boolean {
        return true
    }

    private class SlideActivityAdapter : SlideActivityCallback {
        override val previousActivity: Activity?
            get() = ActivityLifecycleHelper.previousActivity
    }
}